document.getElementById('uploadButton').addEventListener('click', () => {
    const fileInput = document.getElementById('fileInput');
    const status = document.getElementById('status');
    const progress = document.getElementById('uploadProgress');

    if (!fileInput.files.length) {
        status.textContent = '请选择一个文件';
        return;
    }

    const file = fileInput.files[0];

    // 文件大小限制为150MB
    const maxSize = 300 * 1024 * 1024; // 150MB
    if (file.size > maxSize) {
        status.textContent = '文件大小超过300MB，无法上传';
        return;
    }

    const formData = new FormData();
    formData.append('file', file);
    formData.append('filename', file.name); // 添加文件名

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload', true);

    xhr.upload.onprogress = event => {
        if (event.lengthComputable) {
            const percentComplete = (event.loaded / event.total) * 100;
            progress.value = percentComplete;
            progress.hidden = false;
        }
    };

    xhr.onload = () => {
        if (xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            status.textContent = response.error || response.message;
            if (!response.error) {
                refreshFileList(); // 自动刷新文件列表
            }
        } else {
            status.textContent = '上传失败';
        }
        progress.hidden = true;
    };

    xhr.onerror = () => {
        status.textContent = '上传失败';
        progress.hidden = true;
    };

    xhr.send(formData);
});

function refreshFileList() {
    fetch('/list-files')
        .then(response => response.json())
        .then(data => {
            const fileList = document.getElementById('fileList');
            fileList.innerHTML = '';
            data.forEach(file => {
                const li = document.createElement('li');
                li.textContent = `${file.name} (${file.size} bytes)`;
                fileList.appendChild(li);
            });
        })
        .catch(error => {
            console.error('Error fetching file list:', error);
        });
}